using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Microsoft.Win32;

namespace SpellCenter.UI
{
    class SantaFeSynchronizer : IInterApplicationSyncronizer
    {
        private static readonly RegistryKey s_regKey =
            Registry.CurrentUser.CreateSubKey(@"Software\SantaFe\Focus\ScriptureReference");

        private static readonly int s_focusMessage = (int) RegisterWindowMessage("SantaFeFocus");

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint PostMessage(IntPtr p, int focusMessage, uint focusType, int zero);

        #region IInterApplicationLoudMouth Members

        /// <summary>
        /// Move to the specified verse
        /// </summary>
        /// <param name="verse">Verse in "BBB C:V" notation</param>
        public void MoveToVerse(string verse)
        {
            if (!Regex.IsMatch(verse, @"\w{3} \d{1,3}:\d{1,3}"))
                throw new YouDontKnowWhatABibleVerseLooksLikeException(
                    string.Format("'{0}' is not a valid scripture reference, use 'BBB C:V' format", verse));
            s_regKey.SetValue(null, verse);
            PostMessage(new IntPtr(-1), s_focusMessage, (uint) FocusTypes.ScriptureReferenceFocus, 0);
        }

        #endregion

        private enum FocusTypes
        {
            ScriptureReferenceFocus = 1,
        }
    }
}
